﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using Entities;
using Controller;
using System.Data;
using Microsoft.Win32;
using System.IO;
using System.Text.RegularExpressions;

namespace UserInterface
{
    /// <summary>
    /// This is the main UI Window.
    /// </summary>
    public partial class Window1 : Window
    {

        #region Private Members
        private ConnectionInformation connectionInformation;
        private List<string> dataBaselist;
        private TableInformation tableInformation;
        private List<string> tableViewList;
        private List<Column> list;
        private EAVTable eavTable;
        private List<ObjectForBinding> _ObjectForBinding;
        private readonly String[] MyDataTypeComboBoxList = { "Binary", "Boolean", "DateTime", "Double", "Guid", "Int32", "Int64", "String" };
        private int UploadedCount;
        private int NotUploadedCount;
        private Storyboard StartBusy;
        private Storyboard StopBusy;
        private DataTable UploadingStatus;
        private Regex regex;
        private bool connected;

        //Controllers....
        private CheckConnectionController checkConnectionController;
        private GetTableInformationController getTableInformationController;
        private GetTableListController getTableListController;
        private GetViewListController getViewListController;
        private GetViewInformationController getViewInformationController;
        private GetQueryInformationController getQueryInformationController;
        private GenerateEavTableEventController generateEavTableEventController;
        private UploadRelationalTableController uploadRelationalTableController;

        #endregion



        #region Constructor
        public Window1()
        {

            InitializeComponent();

            InitializeControlls();

            checkConnectionController = new CheckConnectionController();
            getTableListController = new GetTableListController();
            getViewListController = new GetViewListController();
            getTableInformationController = new GetTableInformationController();
            getQueryInformationController = new GetQueryInformationController();
            getViewInformationController = new GetViewInformationController();
            generateEavTableEventController = new GenerateEavTableEventController();
            uploadRelationalTableController = new UploadRelationalTableController();

            checkConnectionController.CheckConnectionCompleted += new CheckConnectionEventHandler(checkConnectionController_CheckConnectionCompleted);
            getTableListController.GetTableListCompleted += new GetTableListEventHandler(getTableListController_GetTableListCompleted);
            getViewListController.GetViewListCompleted += new GetViewListEventHandler(getViewListController_GetViewListCompleted);
            getTableInformationController.GetTableInformationCompleted += new GetTableInformationEventHandler(getTableInformationController_GetTableInformationCompleted);
            getTableInformationController.GetFullDataOfTableCompleted += new GetTableInformationEventHandler(getTableInformationController_GetFullDataOfTableCompleted);
            getQueryInformationController.GetQueryInformationCompleted += new GetQueryInformationEventHandler(getQueryInformationController_GetQueryInformationCompleted);
            getViewInformationController.GetViewInformationCompleted += new GetViewInformationEventHandler(getViewInformationController_GetViewInformationCompleted);
            getViewInformationController.GetFullDataOfViewCompleted += new GetViewInformationEventHandler(getViewInformationController_GetFullDataOfViewCompleted);
            generateEavTableEventController.GenerateEavTableCompleted += new GenerateEavTableEventHandler(generateEavTableEventController_GenerateEavTableCompleted);
            uploadRelationalTableController.UploadRelationalTableEventCompleted += new UploadRelationalTableEventHandler(uploadRelationalTableController_UploadRelationalTableEventCompleted);
            uploadRelationalTableController.UploadRowEventCompleted += new UploadRelationalTableEventHandler(uploadRelationalTableController_UploadRowEventCompleted);
            StartBusy = (Storyboard)this.FindResource("StartBusy");
            StopBusy = (Storyboard)this.FindResource("StopBusy");

        }

        #endregion



        #region Private Methods
        private void DisableTabItems(int myStepNumber)
        {
            for (int i = myStepNumber; i < MyTabControl.Items.Count; i++)
                ((TabItem)MyTabControl.Items[i]).IsEnabled = false;
        }

        private void InitializeControlls()
        {
            InitVariables();

            try
            {
                //step1  Server Selection
                CBServerType.SelectedIndex = 0;

                //step2  Connection
                TBServerName.Text = string.Empty;
                RBWinAuthentication.IsChecked = true;
                CBDataBase.ItemsSource = null;
                Bnext2.IsEnabled = false;
                TBlockConnectionStatus.Text = "";

                //step3 Data Source
                RBTable.IsChecked = true;
                CBTableView.ItemsSource = null;
                TBQuery.Text = "Select";

                //step4 Sample Data
                TableDataGrid.DataContext = null;

                //step5 Column mapping
                TableHeaderGrid.DataContext = null;

                //step6 Sample Data
                TableDataGrid2.DataContext = null;

                //step7 Key Selection
                TBPartitionKey.Text = String.Empty;
                TBIncrement.Text = String.Empty;
                RBGuid.IsChecked = true;
                TBStartNumber.Text = String.Empty;
                CBHeader.ItemsSource = null;
                ChkIsImportAsRegular.IsChecked = false;

                //step8 Eav generation
                EAVTableGrid.ItemsSource = null;
                GridEAVTableUpload.ItemsSource = null;


            }
            catch (Exception)
            {
            }

        }

        private void InitVariables()
        {
            dataBaselist = new List<string>();
            tableViewList = new List<string>();
            connectionInformation = new ConnectionInformation();
            regex = new Regex("^[a-z][a-z0-9_]*$", RegexOptions.IgnoreCase);
            connected = false;

            tableInformation = new TableInformation();
            connectionInformation.DataBaseType = DataBaseType.MSSQLServer;
            connectionInformation.AuthenticationMode = AuthenticationMode.MSSQLWindows;
            _ObjectForBinding = new List<ObjectForBinding>();
            eavTable = new EAVTable();
            UploadingStatus = new DataTable();

            UploadingStatus.Columns.Add("PartitionKey");
            UploadingStatus.Columns.Add("RowKey");
            UploadingStatus.Columns.Add("Status");
            UploadingStatus.Columns.Add("Remark");

            UploadedCount = 0;
            NotUploadedCount = 0;

            TBAccountKey.Text = System.Configuration.ConfigurationSettings.AppSettings["AccountKey"];
            TBAccountName.Text = System.Configuration.ConfigurationSettings.AppSettings["AccountName"];
        }

        private void ComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            ComboBox currentCB = sender as ComboBox;
            currentCB.ItemsSource = MyDataTypeComboBoxList;
        }

        //step 1

        //server Selection

        private void CBServerType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DisableTabItems(1);
            try
            {
                if (CBServerType.SelectedIndex == 0)
                {
                    connectionInformation.DataBaseType = DataBaseType.MSSQLServer;
                    connectionInformation.AuthenticationMode = AuthenticationMode.MSSQLWindows;
                    BBrowse2.Visibility = System.Windows.Visibility.Hidden;
                    RBView.IsEnabled = true;
                    TBlockDataBase.Visibility = System.Windows.Visibility.Visible;
                    CBDataBase.Visibility = System.Windows.Visibility.Visible;
                    RBWinAuthentication.IsEnabled = true;
                    RBSQLAuthentication.IsEnabled = true;
                    RBWinAuthentication.Content = "Windows Integrated Authentication";
                    RBSQLAuthentication.Content = "MS SQL Server Authentication";
                    TBlockServerName.Text = "Server Name";
                    TBServerName.IsReadOnly = false;
                    TBServerName.Text = "";
                    TBUserName.Text = "";
                    TBPassword.Password = "";
                    RBSQLAuthentication.IsChecked = true;
                    RBWinAuthentication.IsChecked = true;
                }
                else if (CBServerType.SelectedIndex == 1)
                {
                    connectionInformation.DataBaseType = DataBaseType.MSAccess;
                    connectionInformation.AuthenticationMode = AuthenticationMode.MSAccessWithoutPassword;
                    BBrowse2.Visibility = System.Windows.Visibility.Visible;
                    RBView.IsEnabled = false;
                    TBlockDataBase.Visibility = System.Windows.Visibility.Collapsed;
                    CBDataBase.Visibility = System.Windows.Visibility.Collapsed;
                    RBWinAuthentication.Content = "This file does not contain password.";
                    RBSQLAuthentication.Content = "This file contains password.";
                    TBlockServerName.Text = "Database File";
                    TBServerName.IsReadOnly = true;
                    TBServerName.Text = "";
                    TBUserName.Text = "";
                    TBPassword.Password = "";
                    RBWinAuthentication.IsChecked = true;
                    RBWinAuthentication.IsEnabled = true;
                    RBSQLAuthentication.IsEnabled = false;
                }
                else if (CBServerType.SelectedIndex == 2)
                {
                    connectionInformation.DataBaseType = DataBaseType.MySQL;
                    connectionInformation.AuthenticationMode = AuthenticationMode.MySqlWithoutPassword;
                    BBrowse2.Visibility = System.Windows.Visibility.Hidden;
                    RBView.IsEnabled = true;
                    TBlockDataBase.Visibility = System.Windows.Visibility.Visible;
                    CBDataBase.Visibility = System.Windows.Visibility.Visible;
                    RBWinAuthentication.IsEnabled = true;
                    RBSQLAuthentication.IsEnabled = true;
                    RBWinAuthentication.Content = "Default Authentication";
                    RBSQLAuthentication.Content = "MySQL Server Authentication";
                    TBlockServerName.Text = "Server Name";
                    TBServerName.IsReadOnly = false;
                    TBServerName.Text = "";
                    TBUserName.Text = "";
                    TBPassword.Password = "";
                    RBWinAuthentication.IsChecked = true;
                }
                TBQuery.Text = "select";
                TBlockConnectionStatus.Text = "";
                CBDataBase.ItemsSource = null;
            }
            catch (Exception)
            {
            }
        }

        private void Bnext1_Click(object sender, RoutedEventArgs e)
        {
            TIStep2.IsEnabled = true;
            TIStep2.IsSelected = true;
        }


        //Connection
        private void TBServerName_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(2);
            //Bnext2.IsEnabled = false;
        }

        private void RBSQLAuthentication_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(2);
                Bnext2.IsEnabled = false;

                if (connectionInformation.DataBaseType == DataBaseType.MSSQLServer)
                {
                    TBUserName.IsEnabled = true;
                    connectionInformation.AuthenticationMode = AuthenticationMode.MSSQLServer;
                }
                else if (connectionInformation.DataBaseType == DataBaseType.MSAccess)
                    connectionInformation.AuthenticationMode = AuthenticationMode.MSAccessWithPassword;

                else if (connectionInformation.DataBaseType == DataBaseType.MySQL)
                {
                    TBUserName.IsEnabled = true;
                    connectionInformation.AuthenticationMode = AuthenticationMode.MySqlWithPassword;
                }
                TBPassword.IsEnabled = true;
            }
            catch (Exception)
            {
            }
        }

        private void RBWinAuthentication_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(2);
                Bnext2.IsEnabled = false;
                TBUserName.IsEnabled = false;
                TBPassword.IsEnabled = false;

                if (connectionInformation.DataBaseType == DataBaseType.MSSQLServer)
                    connectionInformation.AuthenticationMode = AuthenticationMode.MSSQLWindows;
                else if (connectionInformation.DataBaseType == DataBaseType.MSAccess)
                    connectionInformation.AuthenticationMode = AuthenticationMode.MSAccessWithoutPassword;
                if (connectionInformation.DataBaseType == DataBaseType.MySQL)
                    connectionInformation.AuthenticationMode = AuthenticationMode.MySqlWithoutPassword;

            }
            catch (Exception)
            {
            }

        }

        private void BConnect_Click(object sender, RoutedEventArgs e)
        {
            BConnect.IsEnabled = false;
            connectionInformation.ServerAddress = TBServerName.Text.Trim();
            CBDataBase.SelectedIndex = -1;
            connectionInformation.DataBaseName = "";
            if (connectionInformation.AuthenticationMode == AuthenticationMode.MSSQLServer || connectionInformation.AuthenticationMode == AuthenticationMode.MySqlWithPassword)
            {
                connectionInformation.UserName = TBUserName.Text.Trim();
                connectionInformation.Password = TBPassword.Password;
                checkConnectionController.CheckConnectionAsyncronus(connectionInformation);
            }
            else
            {
                if (connectionInformation.AuthenticationMode == AuthenticationMode.MSAccessWithPassword)
                    connectionInformation.Password = TBPassword.Password;
                checkConnectionController.CheckConnectionAsyncronus(connectionInformation);
            }
        }

        private void CBDataBase_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                DisableTabItems(2);
                connectionInformation.DataBaseName = e.AddedItems[0].ToString();
            }
            catch (Exception)
            {
            }
        }

        private void BBrowse2_Click(object sender, RoutedEventArgs e)
        {
            TBPassword.IsEnabled = false;
            TBlockConnectionStatus.Text = "";
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory = @"C:\";
            fileDialog.Filter = "MSAccess Files (*.mdb)|*.mdb";
            fileDialog.RestoreDirectory = true;

            Nullable<bool> result = fileDialog.ShowDialog();
            try
            {
                if (result == true)
                {
                    TBServerName.Text = fileDialog.FileName;
                    connectionInformation.ServerAddress = fileDialog.FileName;
                    if (checkConnectionController.IfAccessFileHavingPassword(connectionInformation))
                    {
                        connectionInformation.AuthenticationMode = AuthenticationMode.MSAccessWithPassword;
                        RBSQLAuthentication.IsEnabled = true;
                        RBWinAuthentication.IsEnabled = false;
                        RBSQLAuthentication.IsChecked = true;
                        TBPassword.IsEnabled = true;
                    }
                    else
                    {
                        connectionInformation.AuthenticationMode = AuthenticationMode.MSAccessWithoutPassword;
                        RBWinAuthentication.IsEnabled = true;
                        RBSQLAuthentication.IsEnabled = false;
                        RBWinAuthentication.IsChecked = true;
                        TBPassword.IsEnabled = false;
                        TBPassword.Password = "";
                    }

                }
            }
            catch (UnauthorizedAccessException UnAEx)
            {
                MessageBox.Show(UnAEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        //Authentication mode
        //server name
        //database name
        private void Bnext2_Click(object sender, RoutedEventArgs e)
        {
            TBlockConnectionStatus.Text = "";
            if (RBView.IsChecked == true)
                getViewListController.GetViewList(connectionInformation);
            else if (RBTable.IsChecked == true)
                getTableListController.GetTableList(connectionInformation);
            else
            {
                TIStep3.IsEnabled = true;
                TIStep3.IsSelected = true;
            }

        }

        //Data Source
        private void RBTable_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(3);
                CBTableView.IsEnabled = true;
                BBrowse3.IsEnabled = false;
                TBQuery.IsEnabled = false;
                CBTableView.SelectedIndex = -1;
                if (connected)
                    getTableListController.GetTableList(connectionInformation);
            }
            catch (Exception)
            {

            }

        }

        private void RBView_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(3);
                CBTableView.IsEnabled = true;
                BBrowse3.IsEnabled = false;
                TBQuery.IsEnabled = false;
                CBTableView.SelectedIndex = -1;
                if (connected)
                    getViewListController.GetViewList(connectionInformation);
            }
            catch (Exception)
            {

            }
        }

        private void RBQuery_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(3);
                CBTableView.SelectedIndex = -1;
                CBTableView.IsEnabled = false;
                BBrowse3.IsEnabled = true;
                TBQuery.IsEnabled = true;
            }
            catch (Exception)
            {

            }
        }

        private string tableName = string.Empty;

        private void CBTableView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                tableName = CBTableView.SelectedItem.ToString();
                DisableTabItems(3);
            }
            catch (Exception)
            {
                tableName = "";
            }
        }

        private void BBrowse3_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.InitialDirectory = @"C:\";
            fileDialog.Filter = "Text Files (*.txt)|*.txt";
            fileDialog.RestoreDirectory = true;
            FileStream fileStream;
            StreamReader reader;
            Nullable<bool> result = fileDialog.ShowDialog();
            try
            {
                if (result == true)
                {
                    fileStream = new FileStream(fileDialog.FileName, FileMode.Open);
                    reader = new StreamReader(fileStream);
                    TBQuery.Text = reader.ReadToEnd();
                }
            }
            catch (UnauthorizedAccessException UnAEx)
            {
                MessageBox.Show(UnAEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void Bnext3_Click(object sender, RoutedEventArgs e)
        {
            progressBar1.Value = (double)0.0;
            if (RBQuery.IsChecked == true)
                getQueryInformationController.GetQueryInformation(connectionInformation, TBQuery.Text);
            else
            {
                if (CBTableView.SelectedIndex == -1)
                {
                    MessageBox.Show("Please Select a Table or View");
                }
                else
                {
                    if (RBTable.IsChecked == true)
                        getTableInformationController.GetTableInformation(connectionInformation, tableName);
                    else
                        getViewInformationController.GetViewInformation(connectionInformation, tableName);
                }
            }
        }

        //Sample Data
        private void Bnext4_Click(object sender, RoutedEventArgs e)
        {
            TIStep5.IsEnabled = true;
            TIStep5.IsSelected = true;

            TableHeaderGrid.ItemsSource = null;

            if (RBQuery.IsChecked == true)
                TableHeaderGrid.Columns[4].Visibility = System.Windows.Visibility.Hidden;
            else
                TableHeaderGrid.Columns[4].Visibility = System.Windows.Visibility.Visible;

            _ObjectForBinding.Clear();
            foreach (Column col in tableInformation.ColumnList)
            {
                _ObjectForBinding.Add(new ObjectForBinding() { AzureColumn = Column.DeepCopy(col) });
            }

            TableHeaderGrid.ItemsSource = _ObjectForBinding;

        }

        //Column mapping
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DisableTabItems(5);
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            DisableTabItems(5);
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(5);
        }


        private void Bnext5_Click(object sender, RoutedEventArgs e)
        {
            int columnCount = _ObjectForBinding.Count;
            int i;
            try
            {
                String ExceptionMessage = string.Empty;
                int importCounter = 0;

                for (i = 0; i < columnCount; i++)
                {
                    _ObjectForBinding[i].AzureColumn.Name = _ObjectForBinding[i].AzureColumn.Name.Trim();

                    if (string.IsNullOrEmpty(_ObjectForBinding[i].AzureColumn.Name) && _ObjectForBinding[i].AzureColumn.IsImported == true)
                    {
                        throw new Exception("Please do not leave empty column name.");
                    }

                    if (!regex.IsMatch(_ObjectForBinding[i].AzureColumn.Name, 0) && _ObjectForBinding[i].AzureColumn.IsImported == true)
                        throw new Exception("Invalid column name :" + _ObjectForBinding[i].AzureColumn.Name +
                            "\nNote:\n  1. Column name must start with character.\n  2. Any special symbol or blank space is not allowed.");

                    if (_ObjectForBinding[i].AzureColumn.IsImported == true)
                        importCounter++;

                    for (int j = i + 1; j < columnCount; j++)
                        if (_ObjectForBinding[i].AzureColumn.Name.Equals(_ObjectForBinding[j].AzureColumn.Name) && _ObjectForBinding[i].AzureColumn.IsImported == true && _ObjectForBinding[j].AzureColumn.IsImported == true)
                        {
                            throw new Exception("One or more column having same name");
                        }
                }
                if (importCounter == 0)
                    throw new Exception("Please select at least one column.");

                try
                {
                    eavTable.ColumnList.Clear();
                }
                catch (Exception)
                {
                    eavTable.ColumnList = new List<Column>();
                }

                for (i = 0; i < columnCount; i++)
                {
                    eavTable.ColumnList.Add(_ObjectForBinding[i].AzureColumn);
                    tableInformation.ColumnList[i].IsImported = _ObjectForBinding[i].AzureColumn.IsImported;
                }

                List<Column> list = new List<Column>();

                for (i = 0; i < columnCount; i++)
                    list.Add(Column.DeepCopy(_ObjectForBinding[i].AzureColumn));

                DataTable MyTable = tableInformation.GetRefinedDataTable(list);

                TableDataGrid2.DataContext = MyTable.DefaultView;

                TIStep6.IsEnabled = true;
                TIStep6.IsSelected = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        //Sample Data again
        private void Bnext6_Click(object sender, RoutedEventArgs e)
        {
            TIStep7.IsEnabled = true;
            TIStep7.IsSelected = true;

            try
            {
                CBHeader.Items.Clear();
            }
            catch (Exception)
            { }

            for (int i = 0; i < eavTable.ColumnList.Count; i++)
            {
                if (eavTable.ColumnList[i].IsImported == true)
                    try
                    {
                        tableInformation.DataTable.Columns[i].Unique = true;
                        CBHeader.Items.Add(eavTable.ColumnList[i].Name);
                    }
                    catch (Exception)
                    { }
            }
            if (CBHeader.Items.Count == 0)
            {
                RBGuid.IsChecked = true;
                RBHeader.IsEnabled = false;
                CBHeader.IsEnabled = false;
                ChkIsImportAsRegular.IsEnabled = false;
                TBNoUniqueKey.Visibility = System.Windows.Visibility.Visible;
                CBHeader.Visibility = System.Windows.Visibility.Hidden;
                ChkIsImportAsRegular.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                RBHeader.IsEnabled = true;
                TBNoUniqueKey.Visibility = System.Windows.Visibility.Hidden;
                CBHeader.Visibility = System.Windows.Visibility.Visible;
                ChkIsImportAsRegular.Visibility = System.Windows.Visibility.Visible;
            }

            tableInformation.DataTable.Constraints.Clear();
            EavGridView.DataContext = eavTable;
        }


        //Azure Configuration
        private void Bnext7_click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TBAccountName.Text.Trim()) || string.IsNullOrEmpty(TBAccountKey.Text.Trim()))
                MessageBox.Show("Please enter account name and account key.");
            else if (string.IsNullOrEmpty(TBTableName.Text.Trim()))
                MessageBox.Show("Please enter table name and that must exist in cloud storage.");
            else
            {
                if (RBGuid.IsChecked == true) eavTable.RowKeyType = RowKeyType.Guid;
                if (RBHeader.IsChecked == true) eavTable.RowKeyType = RowKeyType.TableHeader;
                if (RBSequential.IsChecked == true)
                {
                    eavTable.RowKeyType = RowKeyType.SequentialKey;
                    int CheckForInt = 0;

                    if (int.TryParse(TBIncrement.Text, out CheckForInt))
                        eavTable.Increment = CheckForInt;
                    else
                        eavTable.Increment = -100;

                    if (int.TryParse(TBStartNumber.Text, out CheckForInt))
                        eavTable.StartIndex = int.Parse(TBStartNumber.Text);
                    else
                        eavTable.StartIndex = -100;

                }
                if (RBTicks.IsChecked == true) eavTable.RowKeyType = RowKeyType.Ticks;

                if (RBTable.IsChecked == true)
                    getTableInformationController.GetFullDataOfTable(connectionInformation, ref tableInformation);
                else if (RBView.IsChecked == true)
                    getViewInformationController.GetFullDataOfView(connectionInformation, ref tableInformation);
                else
                    generateEavTableEventController.GenerateEavTable(eavTable, connectionInformation, tableInformation, out list);
            }
        }

        // EAV Data Table
        private void GenerateUploadingStatusTable()
        {
            DataRow newRow;
            UploadingStatus.Clear();
            foreach (DataRow row in eavTable.EavTable.Rows)
            {
                newRow = UploadingStatus.NewRow();
                newRow[0] = row["PartitionKey"];
                newRow[1] = row["RowKey"];
                newRow[2] = "Pending";
                UploadingStatus.Rows.Add(newRow);
            }
        }

        private void RBSequential_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(7);
                TBIncrement.IsEnabled = true;
                TBStartNumber.IsEnabled = true;
                ChkIsImportAsRegular.IsEnabled = false;
                CBHeader.IsEnabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void RBGuid_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(7);
                TBIncrement.IsEnabled = false;
                TBStartNumber.IsEnabled = false;
                ChkIsImportAsRegular.IsEnabled = false;
                CBHeader.IsEnabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void RBTicks_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(7);
                TBIncrement.IsEnabled = false;
                TBStartNumber.IsEnabled = false;
                ChkIsImportAsRegular.IsEnabled = false;
                CBHeader.IsEnabled = false;
            }
            catch (Exception)
            {
            }
        }

        private void RBHeader_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                DisableTabItems(7);
                TBIncrement.IsEnabled = false;
                TBStartNumber.IsEnabled = false;
                ChkIsImportAsRegular.IsEnabled = true;
                CBHeader.IsEnabled = true;
            }
            catch (Exception)
            {
            }
        }

        private void TBStartNumber_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(7);

        }

        private void TBIncrement_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(7);
        }

        private void ChkIsImportAsRegular_Checked(object sender, RoutedEventArgs e)
        {
            DisableTabItems(7);
        }

        private void TBAccountName_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(7);
        }

        private void TBPartitionKey_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(7);
        }

        private void TBAccountKey_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(7);
        }

        private void TBTableName_TextChanged(object sender, TextChangedEventArgs e)
        {
            DisableTabItems(7);
        }
        private void CBHeader_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DisableTabItems(7);
        }


        //Displaying Eav Table

        private void BStartUploading_Click(object sender, RoutedEventArgs e)
        {
            DisableTabItems(0);

            eavTable.ColumnList.Clear();

            eavTable.ColumnList = list;

            TIStep9.IsSelected = true;
            TIStep9.IsEnabled = true;

            BStartNew.IsEnabled = false;
            BCancel.IsEnabled = true;

            GridEAVTableUpload.ItemsSource = null;
            GridEAVTableUpload.ItemsSource = UploadingStatus.DefaultView;

            int TotalRows = tableInformation.DataTable.Rows.Count;

            progressBar1.Maximum = TotalRows;

            uploadRelationalTableController.GenerateXMLRowByRowAsync(eavTable, TBAccountName.Text.Trim(), TBAccountKey.Text.Trim(), App.EndPoint, TBTableName.Text.Trim());

        }

        private void BClose_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Do you realy want to stop upload data.", "Warning!!", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                uploadRelationalTableController.AbortProcess();
            }
        }

        private void BStartNew_Click(object sender, RoutedEventArgs e)
        {
            TIStep1.IsEnabled = true;
            TIStep1.IsSelected = true;
            InitializeControlls();
            DisableTabItems(1);
        }

        private void BLaunchCloudStorage_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://onlinedemo.cerebrata.com/Cerebrata.CloudStorage/default.aspx?r=DBUU");
        }

        private void BAboutUs_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.cerebrata.com/?r=DBUU");
        }

        private void BHelp_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.cerebrata.com/Docs/AzureDBUploadutility.UserGuide.pdf");
        }

        #endregion



        #region event Completed Methods

        //In step 2, On requesting connection
        void checkConnectionController_CheckConnectionCompleted(CheckConnectionEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                if (e.exception != null)
                {
                    TBlockConnectionStatus.Text = "Failed";
                    Bnext2.IsEnabled = false;
                    MessageBox.Show(e.exception.Message);
                }
                else if (connectionInformation.DataBaseType == DataBaseType.MSSQLServer)
                {
                    TBlockConnectionStatus.Text = "Successful";
                    CBDataBase.ItemsSource = e.Result;
                    Bnext2.IsEnabled = true;
                    DisableTabItems(2);
                    CBDataBase.Focus();
                }
                else if (connectionInformation.DataBaseType == DataBaseType.MSAccess)
                {
                    TBlockConnectionStatus.Text = "Successful";
                    Bnext2.IsEnabled = true;
                    DisableTabItems(2);
                }
                else if (connectionInformation.DataBaseType == DataBaseType.MySQL)
                {
                    TBlockConnectionStatus.Text = "Successful";
                    CBDataBase.ItemsSource = e.Result;
                    Bnext2.IsEnabled = true;
                    DisableTabItems(2);
                    CBDataBase.Focus();
                }
                StartBusy.Stop();
                StopBusy.Begin();
                BConnect.IsEnabled = true;
                connected = true;
            }));
        }

        //After selection of database we click on next, it populate all list of tabels and views in combo box.
        void getTableListController_GetTableListCompleted(GetTableListEventArgs e)
        {
            if (e.exception != null)
                MessageBox.Show(e.exception.Message);
            else
            {
                CBTableView.ItemsSource = e.Result;
                TIStep3.IsEnabled = true;
                TIStep3.IsSelected = true;
            }
        }

        void getViewListController_GetViewListCompleted(GetViewListEventArgs e)
        {
            if (e.exception != null)
                MessageBox.Show(e.exception.Message);
            else
            {
                CBTableView.ItemsSource = e.Result;
                TIStep3.IsEnabled = true;
                TIStep3.IsSelected = true;
            }
        }

        //Getting metadata and sample data of selected data base object.
        void getTableInformationController_GetTableInformationCompleted(GetTableInformationEventArgs e)
        {
            if (e.exception != null)
                MessageBox.Show(e.exception.Message);
            else if (e.Result.DataTable.Rows.Count == 0)
                MessageBox.Show("No record found in selected table.\nPlease select other table,view or write a query.");
            else
                try
                {
                    tableInformation = e.Result;
                    TableDataGrid.ItemsSource = null;
                    TableDataGrid.ItemsSource = tableInformation.DataTable.DefaultView;
                    TIStep4.IsEnabled = true;
                    TIStep4.IsSelected = true;
                }
                catch (Exception)
                {
                }
        }

        void getViewInformationController_GetViewInformationCompleted(GetViewInformationEventArgs e)
        {
            if (e.exception != null)
                MessageBox.Show(e.exception.Message);
            else if (e.Result.DataTable.Rows.Count == 0)
                MessageBox.Show("No record found in selected view.\nPlease select other table,view or write a query.");
            else
                try
                {
                    tableInformation = e.Result;
                    TableDataGrid.ItemsSource = null;
                    TableDataGrid.ItemsSource = tableInformation.DataTable.DefaultView;
                    TIStep4.IsEnabled = true;
                    TIStep4.IsSelected = true;

                }
                catch (Exception)
                {
                }
        }

        void getQueryInformationController_GetQueryInformationCompleted(GetQueryInformationEventArgs e)
        {
            if (e.exception != null)
                MessageBox.Show(e.exception.Message);
            else if (e.Result.DataTable.Rows.Count == 0)
                MessageBox.Show("No record found as the result of your query.\nPlease write other query or select any table or view.");
            else
            {
                tableInformation = e.Result;
                TableDataGrid.ItemsSource = null;
                TableDataGrid.ItemsSource = tableInformation.DataTable.DefaultView;
                TIStep4.IsEnabled = true;
                TIStep4.IsSelected = true;
            }
        }

        //Retriving full data of table or view just before uploading.
        void getTableInformationController_GetFullDataOfTableCompleted(GetTableInformationEventArgs e)
        {
            if (e.exception != null && e.IsFullDataGet == false)
                MessageBox.Show("Full data of Table could not be retrieved continuing with sample rows." + Environment.NewLine + e.exception.Message);
            generateEavTableEventController.GenerateEavTable(eavTable, connectionInformation, tableInformation, out list);
        }

        void getViewInformationController_GetFullDataOfViewCompleted(GetViewInformationEventArgs e)
        {
            if (e.exception != null && e.IsFullDataGet == false)
                MessageBox.Show("Full data of View could not be retrieved continuing with sample rows." + Environment.NewLine + e.exception.Message);
            generateEavTableEventController.GenerateEavTable(eavTable, connectionInformation, tableInformation, out list);
        }

        //Generating of eav table to be uploaded.
        void generateEavTableEventController_GenerateEavTableCompleted(GenerateEavTableEventArgs e)
        {
            if (e.exception != null)
                MessageBox.Show(e.exception.Message);
            else
            {
                EAVTableGrid.ItemsSource = e.Result.EavTable.DefaultView;
                GenerateUploadingStatusTable();
                TIStep8.IsEnabled = true;
                TIStep8.IsSelected = true;
            }
        }

        //Uploading of one row from eav table is completed.
        void uploadRelationalTableController_UploadRowEventCompleted(UploadRelationalTableEventArgs e)
        {
            StringBuilder StatusReport = new StringBuilder();
            int TotalRows = tableInformation.DataTable.Rows.Count;

            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                if (e.exception != null)
                {
                    NotUploadedCount++;
                    UploadingStatus.Rows[e.RowNumber][2] = "Failed";
                    UploadingStatus.Rows[e.RowNumber][3] = e.exception.Message;
                }
                else
                {
                    UploadedCount++;
                    UploadingStatus.Rows[e.RowNumber][2] = "Succussful";
                }

                StatusReport.Append((e.RowNumber + 1).ToString());
                StatusReport.Append("/");
                StatusReport.Append(TotalRows.ToString());
                StatusReport.Append(" Rows Proccessed.");
                StatusReport.Append(Environment.NewLine);
                StatusReport.Append(UploadedCount.ToString());
                StatusReport.Append(" Rows Uploaded Successfully.");
                StatusReport.Append(Environment.NewLine);
                StatusReport.Append(NotUploadedCount.ToString());
                StatusReport.Append(" Rows failed.");

                TBProgress.Text = StatusReport.ToString();
                TBPercent.Text = e.Progress.ToString() + "% Done.";
                if ((e.RowNumber + 1) <= progressBar1.Maximum)
                    progressBar1.Value = e.RowNumber + 1;
                else
                    progressBar1.Value = e.RowNumber;
            }));
        }

        //Uploading of entire eav table is completed.
        void uploadRelationalTableController_UploadRelationalTableEventCompleted(UploadRelationalTableEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
            {
                if (e.exception != null)
                    MessageBox.Show(e.exception.Message);

                BStartNew.IsEnabled = true;
                BCancel.IsEnabled = false;
                TBProgress.Text = "";
            }));
        }

        #endregion

    }
}
//** if we use step1 for sever selection then replace all 2 by 1 in this mathod.
//## if we use step1 for sever selection then remove this block.
//Change visibility and IsSelect property of TIstep1(Tab Item 1), TIstep2(Tab Item 2) and BBack2(Back Button in step 2).


